<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">

    <link rel="stylesheet" href="/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="/css/style.css">
	<script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="/plugins/bootstrap/js/bootstrap.min.js"></script>

    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="../plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="../plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="../plugins/kindeditor/lang/zh_CN.js"></script>

	<link rel="stylesheet" href="/plugins/select2/select2.css" />
	<link rel="stylesheet" href="/plugins/select2/select2-bootstrap.css" />
	<script src="/plugins/select2/select2.min.js" type="text/javascript"></script>


	<!--bootstrap-fileinput-->
	<script src="/plugins/bootstrap-fileinput/js/fileinput.js"></script>
	<script src="/plugins/bootstrap-fileinput/js/locales/zh.js"></script>
	<link rel="stylesheet" type="text/css" href="/plugins/bootstrap-fileinput/css/fileinput.css"/>


</head>
<body class="hold-transition skin-red sidebar-mini" >

            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>
                            </li>
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>
                            </li>
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>
                            </li>
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>
                            </li>
                        </ul>
                        <!--tab头/-->
						<form id="add_id">
                        <!--tab内容-->
                        <div class="tab-content">

                            <!--表单内容-->
                            <div class="tab-pane active" id="home">

                                <div class="row data-type">
								   <div class="col-md-2 title">商品分类</div>

		                           	  <div class="col-md-10 data">
		                           	  	<table>
											<tr>
												<td>
													<select class="form-control" id="first_id" name="category1Id" onchange="itemCatTwo(this.value)"></select>
												</td>
												<td>
													<select class="form-control select-sm" id="second_id" name="category2Id" onchange="itemCatThree(this.value)"></select>
												</td>
												<td>
													<select class="form-control select-sm" id="third_id" name="category3Id" onchange="itemCatFour(this.value)"></select>
												</td>
												<td >
													模板ID:<input id="typeId" name="typeTemplateId" size="2" type="text" readonly>
												</td>
											</tr>
		                           	  	</table>

		                              </div>


		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control" name="goodsName" id="goodsName"  placeholder="商品名称">
		                           </div>

		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select class="form-control"  id="brand" name="brandId" style="width: 100%"></select>
		                           </div>

								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control" name="caption"  placeholder="副标题" value="">
		                           </div>

		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" class="form-control" name="price" placeholder="价格" value="">
		                           	   </div>
		                           </div>

		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
									   <textarea name="introduction" style="width:800px;height:400px;visibility:hidden;" ></textarea>
                                   </div>

		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">

		                           	<textarea rows="4"  class="form-control"  name="packageList" placeholder="包装列表"></textarea>
		                           </div>

		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4"  class="form-control" name="saleService"  placeholder="售后服务"></textarea>
		                           </div>


                                </div>
                            </div>


                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <button type="button" class="btn btn-default" title="新建" data-target="#uploadModal"  data-toggle="modal"  ><i class="fa fa-file-o"></i> 新建</button>

					             </div>

								 <table class="table table-bordered table-striped table-hover dataTable">
					                    <thead>
					                        <tr>
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
							            </thead>
					                    <tbody id="ptototbody">

					                    </tbody>
								 </table>

                                </div>
                            </div>


							<!--扩展属性-->
							<div class="tab-pane" id="customAttribute" >
								<table class="row data-type" id = "items_text">

								</table>
							</div>


                            <!--规格-->
                            <div class="tab-pane" id="spec">
                            	<div class="row data-type">
	                            	<div class="col-md-2 title">是否启用规格</div>
			                        <div class="col-md-10 data">
			                        	<input type="checkbox" >
			                        </div>
                            	</div>
                            	<p>

                            	<div>

	                                <div class="row data-type" id="specification">


	                                </div>


	                                <div class="row data-type">
	                                	 <table class="table table-bordered table-striped table-hover dataTable" id="table2">
						                    <thead>
						                        <tr>
												    <th class="sorting">屏幕尺寸</th>
													<th class="sorting">网络制式</th>
												    <th class="sorting">价格</th>
												    <th class="sorting">库存</th>
												    <th class="sorting">是否启用</th>
												    <th class="sorting">是否默认</th>
											    </tr>
								            </thead>
						                    <tbody id="table">

						                    </tbody>
									 	</table>

	                                </div>

	                            </div>
                            </div>

                        </div>
                        <!--tab内容/-->
						<!--表单内容/-->
						</form>
                    </div>

                   </div>
                  <div class="btn-toolbar list-toolbar">
				      <button class="btn btn-primary" onclick="insertInfo()"><i class="fa fa-save"></i>保存</button>
				      <button class="btn btn-default" >返回列表</button>
				  </div>

            </section>


<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">

			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
					<td><input  class="form-control" placeholder="颜色" id="color">  </td>
		      	</tr>
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<table>
							<tr>
								<label for="testfile" class="col-sm-2 control-label">图片</label>
								<input type="hidden" name="image" id="myFile">
								<input type="file"  id="testfile" name="image" multiple >
							</tr>
						</table>
		      		</td>
		      	</tr>
			 </table>

		</div>
		<div class="modal-footer">
			<button class="btn btn-success"  data-dismiss="modal" aria-hidden="true" onclick="addForm()">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>
			<input type="hidden" id="categoryid">

			<!-- 正文区域 /-->
			<script type="text/javascript">
				var editor;
				KindEditor.ready(function(K) {
					editor = K.create('textarea[name="introduction"]', {
						allowFileManager : true
					});
				});

				$(function () {
					itemCatOne(0)
					$("#brand").select2();

						$('#testfile').fileinput({
							language: 'zh',    							//汉化
							uploadUrl: '/goods/upload',					//上传地址
							maxFileCount : 5,							//最大上传个数
							enctype : "multipart/form-data",			//预览
							maxFileSize : 10240,						//设置上传文件的大小
							allowedFileExtensions : ["jpg", "png", "gif"],//限制上传类型
							browseClass: 'btn btn-primary',
						});

						//获取阿里云传回来的值
						$("#testfile").on("fileuploaded", function(event, data, previewId, index){
							var imgUrl = data.response.data;
							$("#myFile").val(imgUrl);
						})
				})


				/*上传追加图片*/
				function  addForm(){
					var url = $("#myFile").val();
					var c = $("#color").val();
					$("#ptototbody").append(
							'<tr>'+ '<td>'+ '<div id="div_id"> '+ c +' </div>'+ '</td>'+ '<td>'+ '<img alt="" src="'+url+'" width="100px" height="100px">'+
							'</td>'+ '<td> <button type="button" class="btn btn-default" onclick="deleteInfo(this)" title="删除" ><i class="fa fa-trash-o"></i> 删除</button></td>'+ '</tr>')
				}

				function deleteInfo(obj){
					$(obj).parents("tr").remove()
				}

				function itemCatOne(id) {
					$.ajax({
						url: "/itemCat1/selectById",
						data: {id:id},
						type: "post",
						dataType: "json",
						async: false,
						success: function (info) {
							var str = '';
							var result = info.data;
							str += '<option value="0">请选择</option>'
							for (var i = 0; i < result.length; i++) {
								str += '<option id="one_id" value="'+result[i].id+'">'+result[i].name+'</option>'
							}
							$("#first_id").html(str);

						},error:function (result) {
							console.log(result);
						}
					})
				}

				function itemCatTwo(id) {
					$.ajax({
						url: "/itemCat1/selectById",
						data: {id:id},
						type: "post",
						dataType: "json",
						async: false,
						success: function (info) {
							var str = '';
							var result = info.data;
							str += '<option value="0">请选择</option>'
							for (var i = 0; i < result.length; i++) {
								str += '<option id="one_id" value="'+result[i].id+'">'+result[i].name+'</option>'
							}
							$("#second_id").html(str);

						},error:function (result) {
							console.log(result);
						}
					})
				}

				function itemCatThree(id){
					$.ajax({
						url: "/itemCat1/selectById",
						data: {id:id},
						type: "post",
						dataType: "json",
						async: false,
						success: function (info) {
							console.log(info)
							var str = '';
							var result = info.data;
							str += '<option>请选择</option>'
							for (var i = 0; i < result.length; i++) {
								str += '<option id="one_id" value="'+result[i].id+'">'+result[i].name+'</option>'
							}

							$("#third_id").html(str);

						},error:function (result) {
							console.log(result);
						}
					})
				}

				function itemCatFour(id) {
					$("#categoryid").val(id);
					$.ajax({
						url: "/itemCat1/selectId",
						data: {id: id},
						type: "post",
						dataType: "json",
						async: false,
						success: function (info) {
							console.log(info.data)
							$("#typeId").val(info.data.typeId);
						}, error: function (result) {
							console.log(result);
						}
					})
					itemCatFive()
				}

				function itemCatFive(){
					var id = $("#typeId").val()
					$.ajax({
						url: "/temTemplate/selectByTypeId",
						data: {id:id},
						type: "post",
						dataType: "json",
						async: false,
						success: function (info) {
							console.log(info.data)
							var brand = JSON.parse(info.data.brandIds);
							var str = '';
							for (var i = 0; i < brand.length; i++) {
								str+='<option value="'+brand[i].id+'">'+brand[i].text+'</option>'
							}
							$("#brand").html(str);

							var custom = JSON.parse(info.data.customAttributeItems);
							var str1 = '';
							for (var j = 0; j < custom.length; j++) {
								str1 += '<tr>'
								str1 += '<td>' +custom[j].text+ '</td>'
								str1 += '<td>'
								str1 += '<input className="form-control" placeholder="' +custom[j].text+ '">'
								str1 += '</td>'
								str1 += '</tr>'
							}
							$("#items_text").html(str1)

							//详情见D:\第五阶段\day10_东东商城\资料\解决方案\添加SKU核心代码
							var str2 = '';
							var specIds = info.data.specIds;
							for (var j2 = 0; j2 < specIds.length; j2++) {
								str2 += '<div name="specificationName">'
								str2 += '<div class="col-md-2 title">' + specIds[j2].text + '</div>'
								str2 += '<div class="col-md-10 data">'
								var optionList = specIds[j2].optionList;
								for (var j3 = 0; j3 < optionList.length; j3++) {
									str2 += '<span> <input onclick="checkSpec(this,\'' + specIds[j2].text + '\',\'' +  optionList[j3].optionName + '\')" type="checkbox" >' +  optionList[j3].optionName + '</span>'
								}
								str2 += '</div>'
							}
							$("#specification").html(str2)


							var str3 = ''
							str3 += '<tr>'
							str3 += '<td> 4.0 </td>'
							str3 += '<td>3G</td>'
							str3 += '<td><input className="form-control" placeholder="价格"></td>'
							str3 += '<td><input className="form-control" placeholder="库存数量" id="num"></td>'
							str3 += '<td><input type="checkbox" id="box1"></td>'
							str3 += '<td><input type="checkbox" id="box2"></td>'
							str3 += '</tr>'
							$("#table").html(str3)

						},error:function (result) {
							console.log(result);
						}
					})
				}

				//详情见D:\第五阶段\day10_东东商城\资料\解决方案\添加SKU核心代码
				var items=[];
				function checkSpec(event,name,value) {
					var obj = searchObjectByKey(items,'attributeName',name);
					if(obj != null){
						if ($(event).prop('checked')){//勾选
							obj.attributeValue.push(value);
						}else {//取消勾选
							obj.attributeValue.splice(obj.attributeValue.indexOf(obj),1)//从items中移除规格选项
							//如果规格选项中没哟数据
							if(obj.attributeValue.length == 0){
								//移除items中的数据
								items.splice(items.indexOf(obj),1)
							}
						}
					}else {
						//如果之前没有数据,items新加数据
						items.push({'attributeName':name,'attributeValue':[value]})
					}

				}

				//遍历组装用户勾选规格选项数据  详情见D:\第五阶段\day10_东东商城\资料\解决方案\添加SKU核心代码
				function searchObjectByKey(list,attributeName,attributeValue){
					for(var i=0;i<list.length;i++){
						//如果list中我们选择key存在
						if(list[i][attributeName] == attributeValue){
							return list[i];//返回当前对象
						}
					}
					//遍历结束后都不存在，返回null
					return null;
				}


				function insertInfo() {
					//实例化编辑器对象
					editor.sync();
					//获取编辑器中输入的内容
					$("[name=introduction]").val();

					//商品图片多重增加
					var trs = $("#ptototbody").find("tr");
					var imageList = [];
					for (var i = 0; i < trs.length; i++) {
						var tds = $(trs[i]).find("td");
						var color = $(tds[0]).text();
						var image = $(tds[1]).find("img");
						var url = $(image).attr("src");
						imageList.push({color:color,url:url});
					}
					console.log(imageList);
					var colorImg = JSON.stringify(imageList);

					//扩展属性的增加
					var cus = $("#items_text").find("tr")
					var customAttributeItem = []
					for (var j = 0; j < cus.length; j++) {
						var tds = $(cus[j]).find("td")
						var text = $(tds[0]).text()
						var input = $(tds[1]).find("input")
						var value = $(input).val()
						customAttributeItem.push({text : text, value : value})
					}
					console.log(customAttributeItem);
					var customAttributeItems = JSON.stringify(customAttributeItem)

					//规格转json,规格的网络和机身内存
					var itemsJson = JSON.stringify(items)

					//spec{key:value}
					var  spec = '{"屏幕尺寸":"4.0","网络制式":"3G"}';

					//是否启用$("#box1").prop("checked"),获取checked的值，返回true或者false
					var is_enable_spec = $("#box1").prop("checked");
					var itemSn = "0";
					if (is_enable_spec){
						itemSn = "1";
					}

					//是否默认
					var is_default = $("#box2").prop("checked");
					var isDefault = "0";
					if (is_default){
						isDefault = "1";
					}

					var goodsName = $("#goodsName").val();
					var title = goodsName + "  " + "4.0" + "  "  + "3G"


					var stockCount = $("#num").val();
					var num = $("#num").val();

					var categoryid = $("#categoryid").val();

					var status = "1";
					$.ajax({
						url: "/goods/insertInfo",
						data: $("#add_id").serialize()
								+ "&itemImages=" + colorImg
								+"&customAttributeItems=" +customAttributeItems
								+ "&specificationItems=" + itemsJson
								+ "&spec=" + spec
								+ "&itemSn=" + itemSn
								+ "&isDefault=" + isDefault
								+ "&title=" + title
								+ "&stockCount=" + stockCount
								+ "&num=" + num
								+ "&categoryid=" + categoryid
								+ "&status=" + status,

						type: "post",
						dataType: "json",
						async: false,
						success: function (info) {
							if (info.code == 10000){
								location.reload();
								alert(info.message)
							}
						},error:function (result) {
							console.log(result);
						}
					})
				}

			</script>
</body>

</html>